// components/table-header.js
Component({
  properties: {
    stadiumId: String,
    stadiumName: String,
    sportId: Number,
    appointmentPeriod: String,
  },
  data: {
    dateList: [],
    appointmentValid: [],
  },
  observers: {
    'appointmentPeriod': function (appointmentPeriod) {
      if (!appointmentPeriod) return;
      appointmentPeriod = parseInt(appointmentPeriod)
      const cur = new Date().getTime();
      const dateList = [];
      const dayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      for (let i = 0; i <= appointmentPeriod; i++) {
        const date = new Date(cur + i * 86400000);
        dateList.push({
          dateStr: date.Format('yyyy-MM-dd'),
          dayStr: dayMap[date.getDay()]
        });
      }
      this.setData({ dateList });
      this.loadAppointmentData(dateList[0].dateStr, dateList[dateList.length - 1].dateStr);
    }
  },
  methods: {
    async loadAppointmentData(minDateStr, maxDateStr) {
      const resList = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_appointment',
          data: {
            funcName: 'query',
            searchText: '',
            searchData: { stadium_id: this.data.stadiumId },
            dateRange: [minDateStr, maxDateStr],
          },
          success: (r) => resolve(r.result),
        });
      })
      const resDateList = resList.map(o => parseInt(o.date_ts / 1e5));
      const appointmentValid = this.data.dateList.map(o => {
        const cur = parseInt(new Date(o.dateStr).getTime() / 1e5);
        return resDateList.filter(v => (v == cur)).length > 0;
      })
      this.setData({ appointmentValid });
    },
    onLook(ev) {
      const data = ev.currentTarget.dataset;
      const appointmentId = this.data.stadiumId + '-'
        + parseInt(new Date(data.date).getTime() / 1e5);
      wx.navigateTo({
        url: `/pages/reservation/appointment?appointmentId=${appointmentId}&sportId=${this.data.sportId}`
          + '&disabled=0&payable=1',
        success: (r) => {
          r.eventChannel.emit('userView', {
            dateList: this.data.dateList,
            appointmentValid: this.data.appointmentValid,
            dateIdx: data.idx,
            stadiumName: this.data.stadiumName,
          })
        }
      })
    }
  }
})
